package com.aa.base

/**
 * @author Afra55
 * @date 3/31/21
 * A smile is the best business card.
 */
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.viewbinding.ViewBinding
import com.aa.base.event.EventLiveData
import com.aa.base.event.EventMessage

open class FFragment(var fragmentTag: String):Fragment(){

}
/**
 * @author Afra55
 * @date 2020/4/8
 * A smile is the best business card.
 */
abstract class BaseFragment<T : ViewBinding>(
    var fTag: String
) : FFragment(fTag),
    Observer<EventMessage?> {

    var binding: T? = null

    var isPrepared = false
    private var isLazyLoaded = false
    var isDestroyed = false
    var mActivity: AActivity? = null
    var isResume = false

    abstract fun initBinding(inflater: LayoutInflater,
                             container: ViewGroup?,
                             savedInstanceState: Bundle?): T

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if (binding != null) {
            try {
                val parent = binding?.root?.parent as? ViewGroup
                parent?.removeView(binding?.root)
            } catch (e: Exception) {
            }
        }
        binding = initBinding(inflater, container, savedInstanceState)
        return binding?.root
    }



    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        isPrepared = true
        isDestroyed = false
    }

    override fun onResume() {
        super.onResume()
        lazyLoad()
        isResume = true
    }

    override fun onStop() {
        super.onStop()
        isResume = false
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is AActivity) {
            mActivity = context
        } else {
            throw RuntimeException("wrong activity")
        }
    }

    override fun onDetach() {
        mActivity = null
        super.onDetach()
    }

    override fun onDestroy() {
        isDestroyed = true
        super.onDestroy()
    }

    abstract fun initLogic()

    private fun lazyLoad() {
        if (isPrepared && !isLazyLoaded) {
            initLogic()
            isLazyLoaded = true
            EventLiveData.observe(this, this)
        }
    }

    open fun messageEvent(event: EventMessage){}
    override fun onChanged(t: EventMessage?) {
        if (t != null) {
            messageEvent(t)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }



}